package com.unytech.project.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.SAXException;

import com.unytech.project.entity.system.Permission;


public class PermissionUtil {
	/**
	 * 调用Xml2Permission中的方法，解析权限XML文件
	 * 注意文件路径及每个节点的名称不能有错
	 * 注意返回的List中存放的是权限集合Set，List中的第一个元素是一级菜单的Set，以此类推
	 * @return List  
	 * @throws SAXException 
	 * @throws IOException 
	 * @throws Exception 
	 * 
	 */
	public static List<Permission> getXMLPermission() throws IOException, SAXException {
		Xml2Permission xml2per = new Xml2Permission();
		List<Permission> permlist = new ArrayList<Permission>();
		String root = "tree/item";
		String jiedian = "/item";
		do 
		{
			System.out.println("查找节点："+root);
			xml2per = xml2per.permParse("/Permission.xml", root);
			permlist.addAll(xml2per.getPerms());
			root = root + jiedian;				
		}while(xml2per.getPerms().size() != 0);
				
		return permlist;
	}
	
	/**
	 * 调用Xml2Permission中的方法，把权限XML文件输出为字符串，返回到给前台提供给树形控件dhtmlxTree使用
	 * @return
	 */
	public static String getXMLString() {
		Xml2Permission xml2per = new Xml2Permission();
		String xmlString = xml2per.XML2String("/Permission.xml");
		return xmlString;
	}
	
	public Permission getUriPermissionId(String uri) throws Exception {
		Permission perm = null;
		List<Permission> permissions = getXMLPermission();
		
		for(int i=0; i<permissions.size(); i++) {
			perm = permissions.get(i);
			if (perm.getPermuri().equals(uri)) {
				return perm;
			}
		}
		return null;
	}
}
